package client;
import classes.userBet;
import classes.User;
import java.beans.Statement;
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.MessageDigest.*;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;


/* Request class cotains all the Client's calls
 */

public class Request {

    public String clientIP;
    public int clientPort;
    public Socket clientSocket = null;


/* --- Connection Setup ----
 */
    public void create_connection(String IP, int port){

        clientIP = IP;
        clientPort = port;
     //   BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
       //         System.in));
        // a client socket //
    try {

                clientSocket = new Socket(IP, port);

        } catch (UnknownHostException ex) {// catch the exceptions //
                ex.printStackTrace();
        } catch (IOException ex) {
                ex.printStackTrace();
        }
    }

    public void closeConnection(){
        try {
                clientSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
    }

    }


/* Send a client request (msg) to the server and
 * returns the tokensized response in tokens
 */
    public String[] send (String msg)
    {
//         try {
//            // create_connection("localhost",7000);
//
//                clientSocket = new Socket("localhost", 7000);
//                String s = null;
//                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
//                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//
//                System.out.println("Client sending: " + msg);
//                outToServer.writeBytes(msg);
//
//                System.out.println("GOT HERE");
//
//                s = inFromServer.readLine();
//
//                System.out.println("GOT HERE 2");
//
//                System.out.println("Client received: " + s);
//                String s1 = s.substring(1, s.length());
//
//                System.out.println("Is this what i want? :" + s1);
//
//               tokens = s1.split("><");
//               closeConnection();
//
//            }
//            catch (IOException ex){ ex.printStackTrace();}

        String modifiedSentence = null;
        System.out.println("Client now running");
        // create a buffered reader to get the data from the user through the
        // command line //
        // a client socket //
        Socket cl = null;
        try {
            /**
             * construct the client socket, specify the IP address which is here
             * localhost for the loopback device and the port number at which a
             * connection needs to be initialized.
             */
            cl = new Socket("localhost", 7000);
            // These streams are for the same purpose as in the server side //
            DataOutputStream outToServer = new DataOutputStream(cl.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(
                    new InputStreamReader(cl.getInputStream()));
            // read the user's input from the console. //
            String sentence = msg;
            // send the sentence to the server: note the need to append it with
            // an endline character //
            outToServer.writeBytes(sentence + '\n');
            // listen on the socket and read the reply of the server //
            modifiedSentence = inFromServer.readLine();
        } catch (UnknownHostException ex) {// catch the exceptions //
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println(
                "FROM SERVER: " + modifiedSentence);
        String s1 = modifiedSentence.substring(1, modifiedSentence.length()-1);
        String [] tokens = s1.split("><");

        try {
            // close the socket when done //
            cl.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return tokens;
    }



 /* --- Client calls ----
  */

/* Checks validity of login name and password
 * @return : 0 if user, -1 if invalid
 * server response and -2 if invalid info
 */

    public int login (String email, String pass, User user){

        String msg = "<login><" + email + "><" + pass +">";
        String [] tokens = null;
        tokens = send(msg);

        System.out.println("After send");
        if (tokens[0].equals("user")){

            System.out.println("Login sucessful");
            user.set(Integer.parseInt(tokens[1]), tokens[2], tokens[3], tokens[4], tokens[5]);
            return 0;
        }
        if (tokens[0].equals("error")){
            System.err.println("Login failed");
            return -2;
        }
        System.err.println("Invalid server response");
        return -1;
    }


    public int createAccount(String fname, String lname, String email, String pass,
                String bday, User user) {


        String msg = "<create><" + pass + "><" + fname + "><"
                        + lname + "><" + bday + "><" + email + ">";
        String[] tokens = null;
        tokens = send (msg);

        if (tokens[0].equals("user id")){

            System.out.println("Account created sucessful");
            user.set(Integer.parseInt(tokens[1]),fname, lname, bday, email);
            return 0;       // wouldnt it be better to return create OK ?
        }
        if (tokens[0].equals("error")){

            System.err.println("Error! Could not create user.");
            return -2;
        }
        System.err.println("Server response is invalid");
        return -1;
    }

    public int addComment(int gameID, int userID, String date,
                              String time, String comment){


        String msg = "<addComment><" + gameID + "><" + userID + "><" + date
                          + "><" + time + "><" + comment + ">";
        String[] tokens = null;
        tokens = send(msg);

        if (tokens[0].equals("comment")){
            System.out.println("Comment added");
            return 0;
        }
        if (tokens[1].equals("error")){
            System.err.println("Could not create comment");
            return -2;
        }
        System.err.println("Invalid server response");
            return -1;

    }

    public int addBet(int gameID, int userID, String date,
                          String time, String bet){

        String msg = "<addbet><" + gameID + "><" + userID + "><" + date
                              + "><" + time + "><" + bet + ">";
        String[] tokens = null;
        tokens = send(msg);

        if (tokens[0].equals("bet")){

            System.out.println("Bet accepted");
            return 0;
        }
        if (tokens[1].equals("error")){

            System.err.println("Unable to add bet");
            return -2;
        }
        System.err.println("Invalid server response");
            return -1;

    }

    public userBet[] getBets (int field, String key){

            userBet[] Bets = null;

            String msg = "<getbets><" + field + "><" + key + ">";
            String [] tokens = null ;
            tokens = send(msg);

 //           <getbets> ----> (for user profile?)
 // <bet><n><bet #1 id><game id><user's first and last name><date added><time added><status><bet amount>...<bet #n id><game id><user's first and last name><date added><time added><status><bet amount>
 //   0   1     2           3       4                           5             6        7      8
 // <error><could not get bets>

           

            if (tokens[0].equals("bet")){
                    System.out.println("Bet accepted");
                    int n = Integer.valueOf(tokens[1]);
                    Bets = new userBet[n];
                    for (int i = 0; i<n; i++) {
                        Bets[i] = new userBet();
                    }
                    int i;
                    int k = 7;

                    for (i=0;i<n;i++){
                        System.out.println("Token:"+Integer.parseInt(tokens[i*k+2]));
                        Bets[i].setID(Integer.parseInt(tokens[i * k + 2]));
                        Bets[i].setGame(tokens[i * k + 3]);
                        Bets[i].setDateAdded(tokens[i * k + 5]);
                        // Bets[i].setType(). NEED TO SET TYPE !
                        Bets[i].setStatus(Integer.parseInt(tokens[i * k + 7]));
                        Bets[i].setAmount(Integer.parseInt(tokens[i * k + 8]));

                        System.out.println("ID: "+Bets[i].getID());
                        System.out.println("Game: "+Bets[i].getGame());
                        System.out.println("Date: "+Bets[i].getDateAdded());
                        System.out.println("Status: "+Bets[i].getStatus());
                        System.out.println("Amount: "+Bets[i].getAmount());


                    }
                System.out.println("Created array of Bets. Are you sure of this??");
         //       return 0;
            }

            if (tokens[0].equals("error")){
                    System.err.println("Could not add bet");
                  //  return -2;
            }

          //      System.err.println("Invalid server response");
            //    return -1;

                return Bets;
    }


    public String[] getAllGames(){

       String [] tokens = null;
       String msg = "<getallgames><" + 1 + ">";
       tokens = send(msg);

        if (tokens[0].equals("game")){

            System.out.println("Client request accepted. Got all games");

        }

       if (tokens[1].equals("error")){

           System.err.println("Could not select games");

       }

       System.err.println("Invalid server response! Received : <" + tokens[0] + "><" + tokens[1] + ">");

       return tokens;
    }


    public String[] getGames(String field, String key){

        String isInt = "false" ;
        int fieldi = translateField(field);
        if (fieldi == 1)
            isInt = "true";
        
        String tokens[] = null;
        String msg = "<getgames" + "><" + fieldi +"><"+ key
                      + "><" + isInt + ">";
        tokens = send(msg);

        if (tokens[0].equals("game")){

            System.out.println("Client request accepted. Got all games");
        }
        if (tokens[1].equals("error")){
            System.err.println("Could not select games");
        }

        System.err.println("Invalid server response! Received : <" + tokens[0] + "><" + tokens[1] + ">");
        return tokens;

    }

    public int translateField (String fieldS ){

          if (fieldS.equalsIgnoreCase("ID")){
           return 1;
       }
       if (fieldS.equalsIgnoreCase("Home Team")){
           return 2;
       }
       if (fieldS.equalsIgnoreCase("Away Team")){
           return 3;
       }
       if (fieldS.equalsIgnoreCase("Location")){
           return 4;
       }
       if (fieldS.equalsIgnoreCase("Referee")){
           return 7;
       }
       if (fieldS.equalsIgnoreCase("Date")){
           return 5;
       }
          return 0;
     
    }

}